package conexao;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Vector;
import modelo.Usuario;

public class TratadorConexao extends AbstractConect {

  private static TratadorConexao INSTANCE = null;
  private static Conexao con = null;
  private static ServerSocket ss = null;
  private static Protocolo p = null;
  
  private static boolean listen=true;

  private static ArrayList<Usuario> listUser = new ArrayList();
  
  public static TratadorConexao getInstance() {
    if (TratadorConexao.INSTANCE == null) {
      TratadorConexao.INSTANCE = new TratadorConexao();
    }
    return TratadorConexao.INSTANCE;
  }

  //C(reate)R(etrieve)U(pdate)D(elete)
  public static void conectar() {
    p = new Protocolo();

    try {
      ss = new ServerSocket(4444);

      while (listen) {
        
        //Socket s = ss.accept();
        con = new Conexao(ss);
        con.start();
      }

    } catch (IOException ex) {
    }
  }

  public static void desconectar() throws IOException {
    listen=false;
    ss.close();
    if (con != null) {
      con.disconnect();
    }
  }

  public static void sleep() throws IOException {
    listen=false;
    ss.close();
  }

  public static void bind() {
    try {
      ss.setSoTimeout(0);
      ss.setReuseAddress(true);
    } catch (SocketException ex) {
    }
  }

  public static void send(Conexao c, Vector acao) {
      
      if((Integer)acao.get(0) ==0){
        enviarMSGAll((String)acao.get(1));
      }
      //String outputLine = p.processarInput(acao);
     // c.send(outputLine);
  }

  public static void addConexao(Conexao c) {
    Usuario u = new Usuario(c);
    listUser.add(u);
  }

  public static void enviarMSGAll(String msg) {
    for (int i = 0; i < listUser.size(); i++) {
      Vector v = new Vector();
      v.add(0);
      v.add(msg);
      listUser.get(i).getC().send(v);
    }
  }}